<template>
    <!-- 总监初审待审批 -->
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <searchrevealing>
                <el-tabs v-model="activeTab">
                    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="104px">
                        <el-form-item label="商品编码/69码" prop="content">
                            <el-input v-model="queryParams.content" placeholder="请输入" clearable style="width: 220px"
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="类目" prop="categoryIdArr">
                            <el-cascader v-model="queryParams.categoryIdArr" clearable :options="categoryProps"
                                filterable :props="{ label: 'categoryName', value: 'categoryId', checkStrictly: true }"
                                style="width: 220px" @change="handleChange" placeholder="请选择类目" ref="categoryRef" />
                        </el-form-item>
                        <el-form-item label="商品名称" prop="styleName">
                            <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable
                                style="width: 220px" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="供应商" prop="supplierId">
                            <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable filterable
                                v-selectLoad="selectLoad" :teleported="false" :fit-input-width="true" remote
                                :remote-method="searchQuery" class="supplierSelect" style="width: 220px"
                                :loading="supplierQueryLoading" @clear="handleClear">
                                <el-option v-for="dict in supplierNameOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value">
                                </el-option>
                                <template v-if="supplierLoading">
                                    <div class="supplierSelect_icon">
                                        <el-icon class="el-select-loading__icon">
                                            <Loading />
                                        </el-icon>
                                        <span class="el-select-loading__tips">{{ "正在加载" }}</span>
                                    </div>
                                </template>
                                <template #loading>
                                    <svg class="circular" viewBox="0 0 50 50">
                                        <circle class="path" cx="25" cy="25" r="20" fill="none" />
                                    </svg>
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="研发部" prop="recruiterDeptId">
                            <el-select v-model="queryParams.recruiterDeptId" placeholder="请选择研发部" clearable filterable
                                @change="deptChange" style="width: 220px">
                                <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="研发专员" prop="recruiterUserId">
                            <el-select v-model="queryParams.recruiterUserId" placeholder="请选择研发专员" clearable filterable
                                style="width: 220px">
                                <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.nickName"
                                    :value="dict.userId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="大货视频" prop="bigVideo">
                            <el-select style="width: 220px" v-model="queryParams.bigVideo" placeholder="请选择" filterable
                                clearable>
                                <el-option label="有" value="1" />
                                <el-option label="无" value="0" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="包销时限" prop="packageDeadline">
                            <el-select style="width: 220px" v-model="queryParams.packageDeadline" placeholder="请选择"
                                filterable clearable>
                                <el-option label="3个月" value="3个月" />
                                <el-option label="6个月" value="6个月" />
                                <el-option label="12个月" value="12个月" />
                                <el-option label="永久" value="永久" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <div class="form_button">
                        <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
                        <el-button @click="resetQuery" :loading="loading">重置</el-button>
                    </div>
                </el-tabs>
            </searchrevealing>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <!-- <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
                    </el-col> -->
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'总监初审待审批'"
                        @updateColumn="getColmun"></right-toolbar>
                </el-row>
            </template>
            <el-table v-loading="loading" row-key="id" :data="tableData" border @header-dragend="dragEnd">
                <el-table-column v-for="(item, index) in commodityManage" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                        <div v-if="item.prop == 'hmMechanismsList'">
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[0] ||
                                null,
                                '一') }}
                            </div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[1] ||
                                null,
                                '二') }}
                            </div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[2] ||
                                null,
                                '三') }}
                            </div>
                        </div>
                        <span v-if="item.prop == 'bigVideo'">{{ scope.row.bigVideo ? '有' : '无' }}</span>
                        <span v-if="item.prop == 'recruiterDept'">{{ scope.row.inventFirstLogLast.requestDeptName
                            }}</span>
                        <span v-if="item.prop == 'recruiter'">{{ scope.row.inventFirstLogLast.requestNickName }}</span>
                        <span v-if="item.prop == 'requestTime'">{{ scope.row.inventSecondLogLast.requestTime }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleGoodWarehousing(scope.row)" class="color_theme"
                            style="margin-left: 0px !important">去审批</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableTotal > 0" :total="tableTotal" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" />
        </el-card>

        <!-- 核价 -->
        <commoditymodify @doClose="commoditymodifyClose" :commoditydetailsData="commoditymodifyData"
            :dialogInfoVisible="commoditymodifyVisible"></commoditymodify>
    </div>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance() as any;
import commoditymodify from './commoditymodify.vue'
import { categoryList } from '@/api/system/supplierAddProducts';
import { loginSupplierByRoleList } from '@/api/group/supplier/index'
import { removeInvalidNodes } from '@/utils/index'
import { getUserList, getDeptList } from '@/api/group/qualityControl'
import { ContractTable } from '@/api/group/productSelectionPricing/types';
import { listColumn } from '@/api/system/column';
import { getSecondListInvent, getSecondDetailsByIdInvent } from '@/api/group/productSelectionPricing'
const commodityManage = ref()
const activeTab = ref('qualityControl');
const queryFormRef = ref();
const showSearch = ref(true);
const loading = ref(false);
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    content: '',
    categoryIdArr: [],
    categoryId: '',
    supplierId: '',
    tradeMode: '',
    auditStatus: '',
    styleName: '',
    recruiterUserId: '',
    recruiterDeptId: '',
    warehouse: '',
    discountPrice: '',
    bigVideo: '',
    packageDeadline: '',
})
const columnData = ref()
const tableData = ref([])
const tableTotal = ref(0)
const categoryProps = ref([])
const supplierNameOptions = ref<any[]>([])
const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])
const supplierLoading = ref(true)
const supplierNameDate = ref<any>({
    pageNum: 1,
    pageSize: 10,
    supplierName: ''
})
const supplierQueryLoading = ref(false)
const supplierNametotal = ref()

const commoditymodifyVisible = ref(false)
const commoditymodifyData = ref<ContractTable>()

/** 导出按钮操作 */
const handleExport = () => {
    proxy?.downloadAsync("basic/hmProducts/getTaskSecondHistoryExport", {
        ...queryParams.value,
    }, `组长审批待审批_${new Date().getTime()}.xlsx`)
}

// 查询列表数据
const getList = async () => {
    try {
        loading.value = true;
        const res = await getSecondListInvent(queryParams.value);
        tableData.value = res.rows;
        tableTotal.value = res.total;
        loading.value = false;
    } catch (e) {
    } finally {
        loading.value = false;
    }
}
/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    queryParams.value.categoryId = ''
    recruiterList.value = []
    handleClear();
    handleQuery();
};
// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {
    if (val) {
        queryParams.value.categoryId = val.join(',')
    } else {
        queryParams.value.categoryId = ''
    }
}
// 根据招商部获取招商员
const deptChange = async (event: string) => {
    if (event) {
        const res = await getUserList({ deptId: event })
        recruiterList.value = res.rows
    } else {
        recruiterList.value = []
    }
    queryParams.value.recruiterUserId = ''
}

// 直播机制反显
const computedMechanism = (row: any, numbers: string) => {
    if (row) {
        const price = row.price ? row.price : '-'
        const commission = row.commission ? row.commission + '%' : '-'
        const brokerage = row.brokerage ? row.brokerage + '%' : '-'
        const liveStreamingMechanism = row.liveStreamingMechanism ? row.liveStreamingMechanism : '-'
        const costPrice = row.costPrice ? row.costPrice : '-'
        if (row.cooperationMode) {
            if (row.cooperationMode == '分佣') {
                return '机制' + numbers + ': ' + '售价:' + price + ' 佣金:' + commission + ' 补充佣金:' + brokerage + ' 机制:' + liveStreamingMechanism + ' 成本:' + costPrice
            } else {
                return '机制' + numbers + ': ' + '成本:' + costPrice + ' 机制:' + liveStreamingMechanism
            }
        }
    }
}
/** 去核价 */
const handleGoodWarehousing = async (row: ContractTable) => {
    const res: any = await getSecondDetailsByIdInvent({
        id: row.id,
    });
    res.data.bigVideos = import.meta.env.VITE_APP_PIC_URL + res.data.bigVideo
    commoditymodifyData.value = res.data
    commoditymodifyVisible.value = true
};
// 去核价关闭
const commoditymodifyClose = () => {
    commoditymodifyVisible.value = false
    getList();
};
/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('总监初审待审批')
    commodityManage.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
onMounted(async () => {
    await getColmun()
    await getList()
    getCategoryList()
    getDeptLists()
})
// 查询类目
const getCategoryList = async () => {
    const { data = [] } = await categoryList({})
    categoryProps.value = removeInvalidNodes(data, 'categoryStatus');
}

// 获取供应商列表
const getHmSupplierList = async () => {
    supplierLoading.value = true
    const res = await loginSupplierByRoleList(supplierNameDate.value)
    const reshandle = res.rows.map((item: any) => (
        {
            label: item.supplierName,
            value: item.id
        }
    ))
    supplierNameOptions.value.push(...reshandle)
    supplierNametotal.value = res.total
    supplierLoading.value = false
}
/** select懒加载 */
const selectLoad = async () => {
    if (supplierNameOptions.value.length < supplierNametotal.value) {
        supplierNameDate.value.pageNum++;
        getHmSupplierList()
    }
}
/** 远程搜索 */
const searchQuery = async (query: string) => {
    supplierQueryLoading.value = true
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    supplierNameDate.value.supplierName = query
    await getHmSupplierList()
    supplierQueryLoading.value = false
}
/** 清空供应商 */
const handleClear = () => {
    supplierNameDate.value.supplierName = ''
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    getHmSupplierList()
}
// 获取招商部
const getDeptLists = async () => {
    const res = await getDeptList({ parentId: '1856176843717799937' })
    deptList.value = res.data
}
</script>

<style lang="scss" scoped>
.supplierSelect {
    :deep(.el-popper) {
        left: 0 !important;
        top: 34px !important;
        z-index: 7000 !important;
        width: 100% !important;
    }
}

.circular {
    display: inline;
    height: 30px;
    width: 30px;
    animation: loading-rotate 2s linear infinite;
}

.path {
    animation: loading-dash 1.5s ease-in-out infinite;
    stroke-dasharray: 90, 150;
    stroke-dashoffset: 0;
    stroke-width: 2;
    stroke: var(--el-color-primary);
    stroke-linecap: round;
}

.supplierSelect_icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

.el-select-loading__tips {
    color: #606266;
    font-size: 14px;
}

:deep(.el-tabs__content) {
    overflow: visible !important;
}

.el-select-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: initial;
    pointer-events: none;
    color: var(--el-color-info);
    font-size: 12px;

    &__icon {
        font-size: 16px;
        animation: rotate 1.5s linear infinite;
    }

    &__tips {
        margin-left: 6px;
    }

    @keyframes rotate {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }
}
</style>